import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { Button, List, Modal, Stepper, Toast, DatePicker } from "antd-mobile";
import { Row, Col, Card } from "antd";
import { request } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH, PAGE_TYPE, encodeUrlParam } from "src/projects/app/util-tool";
import { getUuid } from "src/business/util_tool";
import './index.less';

// TODO: 平台id以及慈善id均写死
const divideTitleMap = {
    '平台': '7e7e2fec-d91d-11e9-8e1d-983b8f0bcd67',
    '慈善': '567c9bd8-0208-11ea-9b57-7c2a3115762d',
    '服务商': ''
};
/**
 * 组件：食物列表页面视图控件状态
 */
export interface CleanListViewState extends ReactViewState {
    btnState?: any;
    food_list?: any;
    modal?: any;
    list?: any;
    menu_list?: any;
    tabs?: any;
    buy_list?: any;
    price?: any;
    tab_show_list?: any;
    clean_data?: any;
    visible?: any;
    buy_info?: any;
}
/**
 * 组件：食物列表页面视图控件
 */
export class CleanListView extends ReactView<CleanListViewControl, CleanListViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            btnState: [],
            // list: [{ 'id': 1, 'food_name': '打扫房间', 'food_detail': '...', 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572521604937&di=b25d6c8984070b81e08bf353b1755dc5&imgtype=0&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F99%2F64%2F5984bfbfa9e94_610.jpg', 'price': 50 },
            // { 'id': 2, 'food_name': '清洗衣服', 'food_detail': '...', 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572521639479&di=c913af65cf6bb261c50654534334d575&imgtype=0&src=http%3A%2F%2Fwww.tbw-xie.com%2FtuxieJDEwLmFsaWNkbi5jb20vaTQvMjI2MDI2MDQ0Ny9UQjJYOHFiY1BneV91SmpTWlNnWFhiejBYWGFfISEyMjYwMjYwNDQ3JDk.jpg', 'price': 100 },
            // { 'id': 3, 'food_name': '剪发', 'food_detail': '...', 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': 'http://img4.imgtn.bdimg.com/it/u=2884420034,1776269664&fm=26&gp=0.jpg', 'price': 30 }],
            food_list: [],
            buy_list: [],
            modal: false,
            price: 0,
            tab_show_list: [],
            clean_data: [],
            visible: false,
            buy_info: {},
        };
    }
    componentDidMount() {
        let id = this.props.match!.params.key;
        console.log(id);
        // 根据服务商id获取服务产品
        request(this, AppServiceUtility.service_package_service.get_service_product_package_list!({ org_id: id, service_product_type: "助洁服务" }, undefined, undefined))
            .then((data: any) => {
                console.log(data);
                if (data.result.length > 0) {
                    let list = this.state.clean_data;
                    data.result.map((item: any) => {
                        list.push(
                            { 'id': item.id, 'food_name': item.name, 'food_detail': item.introduce, 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': item.picture_collection, 'price': item.total_price, 'proportion': item.proportion, 'organization_id': item.organization_id, 'is_allowance': item.is_allowance }
                        );
                    });
                    this.setState({
                        clean_data: list
                    });
                    this.listChange();
                }
            });
        // this.listChange();
    }
    goPayment = (e: any) => {
        e.nativeEvent.stopImmediatePropagation();
        e.stopPropagation();
        let uuid = getUuid();
        console.log(JSON.stringify(this.state.buy_list));
        const { buy_list } = this.state;
        let divide = {};
        let buy_info: any = [];
        if (this.state.buy_list.length > 0) {
            buy_list.map((item: any) => {
                item['proportion'].map((e: { title: string, contents: number }, i: number) => {
                    switch (e.title) {
                        case "平台":
                            divide['平台'] = {
                                id: divideTitleMap['平台'],
                                percent: e.contents
                            };
                            break;
                        case "服务商":
                            divide["服务商"] = {
                                id: divideTitleMap["服务商"],
                                percent: e.contents
                            };
                            break;
                        case "慈善":
                            divide['慈善'] = {
                                id: divideTitleMap['慈善'],
                                percent: e.contents
                            };
                            break;
                        default:
                            break;
                    }
                });
                buy_info.push({
                    id: item.id,
                    price: item.price,
                    num: item.num,
                    amount_total: item.price * item.num,
                    picture_collection: item.image,
                    subsidy: item.is_allowance === 1 ? item.price : 0,
                    abstract: item.name,
                    pt_id: divide['平台']['id'],
                    pt_percent: divide['平台']['percent'],
                    fw_id: item.organization_id,
                    fw_percent: divide['服务商']['percent'],
                    cs_id: divide['慈善']['id'],
                    cs_percent: divide['慈善']['percent'],
                    // 备注（必要）
                    remarks: '居家服务商品',
                });
            });
            const paramToSend = {
                page_type: PAGE_TYPE.BUY,
                page_info: buy_info,
                // 商户唯一订单号（必要）
                out_trade_no: uuid,
                product_desc: "助洁购买",
                success_url: ROUTE_PATH.paymentSucceed,
                fail_url: ROUTE_PATH.paymentFail,
            };
            const paramToSendStr = JSON.stringify(paramToSend);
            this.props.history!.push(ROUTE_PATH.cleanSubmitOrder + '/' + encodeUrlParam(paramToSendStr));
        } else {
            Toast.fail('你还未选择商品！！！', 1);
        }
    }
    onClose = () => {
        this.setState({
            modal: false,
        });
    }
    showModal = (e: any) => {
        e.preventDefault(); // 修复 Android 上点击穿透
        this.setState({
            modal: true,
        });
    }
    // 添加购物车
    addFood = (id: any, name: any, price: any, food_detail: any, image: any, time: any, is_allowance: any, proportion: any, organization_id: any) => {
        console.log(id + ">>>>>>>" + name);
        // 拿到食物的id
        let buy_list = this.state.buy_list;
        buy_list.push({ 'id': id, 'name': name, 'num': 1, 'price': price, 'food_detail': food_detail, 'image': image, "time": time, 'is_allowance': is_allowance, 'proportion': proportion, 'organization_id': organization_id });
        let list = this.state.btnState;
        list.map((item: any) => {
            if (item.id === id) {
                item.state = true;
            }
        });
        console.log(list);
        console.log(buy_list);
        let allPrice = this.state.price + price;
        this.setState({
            buy_list,
            btnState: list,
            price: allPrice,
            visible: true
        });
        Toast.success('加入购物车成功！！', 1);
        this.listChange();
        this.btnDisable(id);
    }
    // 查找按钮的状态
    btnDisable = (id: any) => {
        if (this.state.btnState.length > 0) {
            let btnState = false;
            this.state.btnState.map((item: any) => {
                if (item.id === id) {
                    return btnState = item.state;
                }
            });
            console.log(btnState);
            return btnState;
        }
        return false;
    }
    // 购物详情数量变化回调
    stepChange = (value: any, id: any, day: any, time: any, price: any, tabIndex: any) => {
        console.log(value);
        let list = this.state.buy_list;
        let btnState = this.state.btnState;
        let allPrice = 0;
        console.log("list>>>>>>>>>", list);
        list.map((item: any, index: any) => {
            if (value === 0) {
                if (item.id === id) {
                    allPrice = this.state.price - price;
                    list.splice(index, 1);
                    btnState.map((items: any) => {
                        if (items.id === id) {
                            items.state = false;
                        }
                    });
                    this.listChange();
                }
            } else {
                if (item.id === id) {
                    console.log(value);
                    // allPrice = value * price;
                    if (value >= item.num) {
                        allPrice = this.state.price + price;
                    } else {
                        allPrice = this.state.price - price;
                    }
                    item.num = value;
                    this.listChange();
                }
            }
        });

        this.setState({
            buy_list: list,
            btnState,
            price: allPrice
        });
    }
    // 根据星期几以及早餐还是午餐查询对应的服务产品
    listChange = () => {
        let food_list: any = [];
        this.state.clean_data.map((item: any, index: any) => {
            let list = this.state.btnState;
            if (list.length > 0) {
                let idList: any = [];
                list.map((listItem: any) => {
                    idList.push(listItem.id);
                });
                if (!idList.includes(item.id)) {
                    list.push({ 'id': item.id, 'state': false });
                    this.setState({
                        btnState: list
                    });
                } else {
                    this.setState({
                        btnState: list
                    });
                }
            } else {
                list.push({ 'id': item.id, 'state': false });
                this.setState({
                    btnState: list
                });
            }
            console.log(this.state.btnState);
            let food = (
                <div className="clean-list" key={item.id} onClick={() => this.goDetails(item.id)} style={{ margin: '0px' }}>
                    <Card className='list-conten'>
                        <Row type='flex' justify='center'>
                            <Col className='list-col' span={12}><img src={item.image} style={{ height: '72pt', width: '130px' }} /></Col>
                            <Col span={12} className='list-col'>
                                <Row><strong>{item.food_name}</strong></Row>
                                <Row>
                                    {/* <Col span={10}>
                                                            {item.food_detail.map((item: any, index: any) => {
                                                                return <p style={{ marginBottom: '0px' }} key={index}>{item.option_content}</p>;
                                                            })}
                                                        </Col> */}
                                    {/* <span>￥{item.price}</span> */}
                                    <Button disabled={this.btnDisable(item.id)} type="warning" size="small" style={{ float: "right" }} onClick={(e: any) => { this.showDatePicker(e, item.id, item.food_name, item.price, item.food_detail, item.image, item.is_allowance, item.proportion, item.organization_id); }}>购买</Button>
                                </Row>
                                <Row>￥{item.price}</Row>
                                {/* <Row>
                                    <Col span={12}>剩余:{item.surplus}</Col>
                                    <Col span={12}>已售:{item.sell}</Col>
                                </Row> */}
                            </Col>
                        </Row>
                    </Card>
                </div>
            );
            food_list.push(food);
            this.setState({
                food_list
            });
        });
    }
    // 跳转到详情页
    goDetails = (id: any) => {
        // e.nativeEvent.stopImmediatePropagation();
        // e.stopPropagation();
        this.props.history!.push(ROUTE_PATH.foodDetails + '/' + id);
    }
    // 显示日期框
    showDatePicker = (e: any, id: any, name: any, price: any, food_detail: any, image: any, is_allowance: any, proportion: any, organization_id: any) => {
        e.stopPropagation();
        let list = { id, name, price, food_detail, image, is_allowance, proportion, organization_id };
        console.log(list);
        this.setState({
            visible: true,
            buy_info: list
        });
    }
    // 日期框确定回调
    DatePickerOK = () => {
        this.setState({
            visible: false
        });
    }
    //  日期框取消回调
    DatePickerCancel = () => {
        this.setState({
            visible: false
        });
    }
    //  日期框值改变事件
    DatePickerChange = (value: any) => {
        console.log(this.formatDate(value));
        let { id, name, price, food_detail, image, is_allowance, proportion, organization_id } = this.state.buy_info;
        this.addFood(id, name, price, food_detail, image, this.formatDate(value),is_allowance, proportion, organization_id);
    }
    // 处理时间
    formatDate = (date: any) => {
        const pad = (n: any) => n < 10 ? `0${n}` : n;
        const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
        const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
        return `${dateStr} ${timeStr}`;
    }
    render() {
        return (
            <div style={{ paddingLeft: '6px', paddingRight: '6px' }}>
                <div className="clean-list-content">
                    {this.state.food_list.length > 0 ? this.state.food_list.map((item: any) => {
                        return item;
                    })
                    :
                    <div  style={{textAlign:'center'}}>该服务商暂时没有服务产品</div>
                    }
                </div>
                <div style={{ overflow: 'hidden', backgroundColor: '#1890ff', width: '90%', height: '35px', position: 'fixed', bottom: '0px', left: '0px', borderRadius: '15px', marginLeft: '15px', marginRight: '15px' }}>
                    <div style={{ float: 'left', width: '50%', textAlign: 'center', lineHeight: '35px' }} onClick={this.showModal}>选购详情</div>
                    <div style={{ float: 'right', width: '30%', textAlign: 'center', lineHeight: '35px', borderLeft: "1px solid rgb(14, 12, 12)" }} onClick={this.goPayment}>确认订单</div>
                </div>
                <Modal
                    popup={true}
                    visible={this.state.modal}
                    onClose={this.onClose}
                    animationType="slide-up"
                    style={{ overflow: 'scroll', height: '300px' }}
                    className='clean-list-modal'
                >
                    <List renderHeader={() => <div>选购详情</div>} style={{ overflow: 'scroll' }}>
                        {this.state.buy_list.map((item: any) => (
                            <List.Item key={item.id} style={{ overflow: 'scroll' }}>{item.name}<Stepper key={item.id} value={item.num} showNumber={true} max={10} min={0} onChange={(value) => { this.stepChange(value, item.id, item.day, item.time, item.price, item.index); }} /></List.Item>
                        ))}
                        <List.Item>
                            <Button type="primary" onClick={this.onClose} style={{ position: 'fixed', bottom: '0px', width: '100%', left: '0px' }}>￥{this.state.price}</Button>
                        </List.Item>
                    </List>
                </Modal>
                <DatePicker
                    visible={this.state.visible}
                    onOk={this.DatePickerOK}
                    onDismiss={this.DatePickerCancel}
                    onChange={(value: any) => { this.DatePickerChange(value); }}
                    title="请选择服务时间"
                />
            </div>
        );
    }
}

/**
 * 组件：食物列表页面视图控件
 * 控制食物列表页面视图控件
 */
@addon('CleanListView', '食物列表页面视图控件', '控制食物列表页面视图控件')
@reactControl(CleanListView, true)
export class CleanListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}